<template>
  <view class="bg-white min-h-screen">
    <!-- 搜索头部 -->
    <view class="px-4 py-3 border-b border-slate-100">
      <view class="flex items-center">
        <button class="p-2" @tap="goBack">
          <text class="iconfont icon-arrow-left text-slate-800"></text>
        </button>
        <view class="flex-1 mx-2 relative">
          <input class="w-full py-2 pl-10 pr-4 bg-slate-100 rounded-full text-sm" type="text" v-model="searchQuery"
            placeholder="搜索习惯、目标或项目" confirm-type="search" @confirm="performSearch" focus />
          <text class="iconfont icon-search absolute left-4 top-half -translate-y-half text-slate-400"></text>
          <button v-if="searchQuery" class="absolute right-3 top-half -translate-y-half p-1" @tap="clearSearch">
            <text class="iconfont icon-close text-xs text-slate-400"></text>
          </button>
        </view>
        <button class="p-2" @tap="goBack">
          <text class="text-indigo-600">取消</text>
        </button>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="px-5 py-4" v-if="!searchQuery && searchHistory.length > 0">
      <view class="flex justify-between items-center mb-3">
        <text class="text-base font-medium text-slate-800">搜索历史</text>
        <button class="p-1" @tap="clearHistory">
          <text class="text-xs text-slate-500">清除</text>
        </button>
      </view>
      <view class="flex flex-wrap gap-2">
        <button v-for="(item, index) in searchHistory" :key="index"
          class="px-3 py-1-5 bg-slate-100 rounded-full text-sm text-slate-600" @tap="useHistoryItem(item)">
          {{ item }}
        </button>
      </view>
    </view>

    <!-- 搜索建议 -->
    <view class="px-5 py-4" v-if="searchQuery && !isSearched">
      <view class="mb-3">
        <text class="text-base font-medium text-slate-800">搜索建议</text>
      </view>
      <view>
        <view v-for="(suggestion, index) in searchSuggestions" :key="index"
          class="py-3 flex items-center border-b border-slate-100" @tap="useSearchSuggestion(suggestion)">
          <text class="iconfont icon-search text-slate-400 mr-3"></text>
          <text class="text-slate-600">{{ suggestion }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';

// 搜索状态
const searchQuery = ref('');
const isSearched = ref(false);
const selectedCategory = ref('all');
const searchHistory = ref<string[]>([]);

// 搜索建议
const searchSuggestions = computed(() => {
  if (!searchQuery.value) return [];

  // 这里可以根据输入生成搜索建议
  return [
    searchQuery.value,
    searchQuery.value + ' 习惯',
    searchQuery.value + ' 目标',
    searchQuery.value + ' 项目'
  ];
});

// 模拟数据
interface Habit {
  id: string;
  title: string;
  icon: string;
  color: string;
  frequency: string;
  completionRate: number;
}

interface Goal {
  id: string;
  title: string;
  icon: string;
  type: 'learning' | 'fitness' | 'career' | 'finance' | 'personal';
  progress: number;
}

interface Project {
  id: string;
  title: string;
  status: 'planning' | 'in_progress' | 'completed' | 'on_hold';
  progress: number;
}

// 搜索结果
const habitResults = ref<Habit[]>([]);
const goalResults = ref<Goal[]>([]);
const projectResults = ref<Project[]>([]);

// 总结果数
const totalResults = computed(() => {
  return habitResults.value.length + goalResults.value.length + projectResults.value.length;
});

// 初始化
onMounted(() => {
  // 从本地存储加载搜索历史
  try {
    const history = uni.getStorageSync('searchHistory');
    if (history) {
      searchHistory.value = JSON.parse(history);
    }
  } catch (e) {
    console.error('Failed to load search history', e);
  }
});

// 执行搜索
const performSearch = () => {
  if (!searchQuery.value.trim()) return;

  // 添加到搜索历史
  if (!searchHistory.value.includes(searchQuery.value)) {
    searchHistory.value.unshift(searchQuery.value);
    // 限制历史记录数量
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10);
    }
    // 保存到本地存储
    uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value));
  }

  // 模拟搜索结果
  isSearched.value = true;

  // 模拟习惯结果
  habitResults.value = [
    {
      id: 'habit-001',
      title: '晨跑',
      icon: 'icon-running',
      color: '#ef4444',
      frequency: '工作日',
      completionRate: 85
    },
    {
      id: 'habit-002',
      title: '阅读',
      icon: 'icon-book',
      color: '#3b82f6',
      frequency: '每天',
      completionRate: 70
    }
  ];

  // 模拟目标结果
  goalResults.value = [
    {
      id: 'goal-001',
      title: '学习前端开发',
      icon: 'icon-code',
      type: 'learning',
      progress: 45
    }
  ];

  // 模拟项目结果
  projectResults.value = [
    {
      id: 'project-001',
      title: '移动应用开发项目',
      status: 'in_progress',
      progress: 45
    }
  ];
};

// 清除搜索
const clearSearch = () => {
  searchQuery.value = '';
  isSearched.value = false;
};

// 清除历史
const clearHistory = () => {
  uni.showModal({
    title: '清除搜索历史',
    content: '确定要清除所有搜索历史吗？',
    success: (res) => {
      if (res.confirm) {
        searchHistory.value = [];
        uni.removeStorageSync('searchHistory');
      }
    }
  });
};

// 使用历史项
const useHistoryItem = (item: string) => {
  searchQuery.value = item;
  performSearch();
};

// 使用搜索建议
const useSearchSuggestion = (suggestion: string) => {
  searchQuery.value = suggestion;
  performSearch();
};

// 选择分类
const selectCategory = (category: string) => {
  selectedCategory.value = category;
};

// 获取目标类型颜色
const getGoalTypeColor = (type: string) => {
  switch (type) {
    case 'learning': return '#3b82f6';
    case 'fitness': return '#10b981';
    case 'career': return '#8b5cf6';
    case 'finance': return '#f59e0b';
    case 'personal': return '#ec4899';
    default: return '#6b7280';
  }
};

// 获取目标类型样式类
const getGoalTypeClass = (type: string) => {
  switch (type) {
    case 'learning': return 'bg-blue-100 text-blue-600';
    case 'fitness': return 'bg-green-100 text-green-600';
    case 'career': return 'bg-purple-100 text-purple-600';
    case 'finance': return 'bg-yellow-100 text-yellow-600';
    case 'personal': return 'bg-pink-100 text-pink-600';
    default: return 'bg-slate-100 text-slate-600';
  }
};

// 获取目标类型名称
const getGoalTypeName = (type: string) => {
  switch (type) {
    case 'learning': return '学习';
    case 'fitness': return '健身';
    case 'career': return '职业';
    case 'finance': return '财务';
    case 'personal': return '个人';
    default: return '其他';
  }
};

// 获取项目状态样式类
const getProjectStatusClass = (status: string) => {
  switch (status) {
    case 'planning': return 'bg-slate-100 text-slate-600';
    case 'in_progress': return 'bg-blue-100 text-blue-600';
    case 'completed': return 'bg-green-100 text-green-600';
    case 'on_hold': return 'bg-yellow-100 text-yellow-600';
    default: return 'bg-slate-100 text-slate-600';
  }
};

// 获取项目状态名称
const getProjectStatusName = (status: string) => {
  switch (status) {
    case 'planning': return '规划中';
    case 'in_progress': return '进行中';
    case 'completed': return '已完成';
    case 'on_hold': return '已暂停';
    default: return '规划中';
  }
};

// 导航到习惯详情
const navigateToHabit = (id: string) => {
  uni.navigateTo({
    url: `/subPages/habit/detail?id=${id}`
  });
};

// 导航到目标详情
const navigateToGoal = (id: string) => {
  uni.navigateTo({
    url: `/subPages/goal/detail?id=${id}`
  });
};

// 导航到项目详情
const navigateToProject = (id: string) => {
  uni.navigateTo({
    url: `/subPages/project/detail?id=${id}`
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style>
/* 添加额外的图标 */
.icon-arrow-left:before {
  content: '\e628';
}

.icon-search:before {
  content: '\e632';
}

.icon-close:before {
  content: '\e633';
}

.icon-chevron-right:before {
  content: '\e629';
}

.icon-running:before {
  content: '\e640';
}

.icon-book:before {
  content: '\e641';
}

.icon-code:before {
  content: '\e642';
}
</style>